// http://www.dreamincode.net/forums/topic/38672-creating-a-server-to-serve-clients/
// http://www.coderanch.com/t/205325/sockets/java/send-any-java-Object-through

import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
/**
 * This handles all of the clients in the room.
 * It accepts new connections and adds them to the room.
 * It is a runnable thread and when the start method is called, it will accept clients.
 */
public class Server{
	private static final int PORT = 52200;
	
	private ServerSocket serverSocket;
	private InetAddress hostAddress;
	private Socket socket;
	
	public static void main(String[] args)
	{
		Server server = new Server();
		server.run(); 
	}
	
	/**
	 * Creates a new room for clients to connect to.
	 */
	public Server()
	{
		// Attempt to get the host address
		try
		{
			hostAddress = InetAddress.getLocalHost();
		}
		catch(UnknownHostException e)
		{
			System.out.println("Could not get the host address.");
			return;
		}
		
		// Announce the host address
		System.out.println("Server host address is: "+hostAddress);
		
		// Attempt to create server socket
		try
		{
			serverSocket = new ServerSocket(PORT);
			//serverSocket = new ServerSocket(9090, 0, InetAddress.getByName("localhost"));
		}
		catch(IOException e)
		{
			System.out.println("Could not open server socket.");
			return;
		}
		
		
		ConnectionHandler.addSearchingGamesToQueue();
		
		// Announce the socket creation
		System.out.println("Socket "+serverSocket+" created.");
	}
	
	/**
	 * Starts the client accepting process.
	 */
	public void run()
	{
		// Announce the starting of the process
		System.out.println("Room has been started.");
		// Enter the main loop
		while(true)
		{
			// Get a client trying to connect
			try
			{
				socket = serverSocket.accept();
				System.out.println("Got Something!");
				new ConnectionHandler(socket);
			}
			catch(IOException e)
			{
				System.out.println("Could not get a client.");
			}
			
		}
	}
}